package com.augn.service.impl;

import com.augn.entity.PostEvaluateMain;
import com.augn.entity.Result;
import com.augn.mapper.PostEvaluateMainMapper;
import com.augn.service.IPostEvaluateMainService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author augn
 * @since 2022-09-22
 */
@Service
public class PostEvaluateMainServiceImpl extends ServiceImpl<PostEvaluateMainMapper, PostEvaluateMain> implements IPostEvaluateMainService {

    @Autowired
    private PostEvaluateMainMapper mapper;

    // 新增一个商品主评价
    @Override
    public Result<?> insertOnePostEvaluateMain(PostEvaluateMain PostEvaluateMain) {
        int insert = mapper.insert(PostEvaluateMain);
        if(insert==0){
            return Result.error("-1","新增失败");
        } else{
            return Result.success(insert);
        }
    }

    //删除一个商品主评价
    @Override
    public Result<?> deleteOnePostEvaluateMain(Integer id) {
        int delete = mapper.deleteById(id);
        if(delete==0){
            return Result.error("-1","删除失败");
        } else{
            return Result.success(delete);
        }
    }

    // 获取一个帖子的主评价及完整的全部从评价
    @Override
    public Result<?> getPartPostEvaluateMain(Integer id, Integer pageNum, Integer pageSize) {

        List<PostEvaluateMain> postEvaluate;
        Map<String,Object> ret = new HashMap<>();
        QueryWrapper<PostEvaluateMain> wrapper= new QueryWrapper<>();

        if (pageSize == null) {
            pageSize = 20;
        }
        if(pageNum==0||pageNum==1){
            pageNum = 0;
        } else {
            pageNum=(pageNum-1)*pageSize;
        }

        postEvaluate = mapper.getPartPostEvaluateMain(id, pageNum, pageSize);

        wrapper.eq("post_id",id);
        Long total = mapper.selectCount(wrapper);
        ret.put("evaMainList",postEvaluate);
        ret.put("pages",total/pageSize==0?1:total/pageSize);
        ret.put("total",total);

        if (postEvaluate.isEmpty()) {
            return Result.error("-1", "该帖子暂无评论");
        } else {
            return Result.success(ret);
        }
    }
}
